﻿using Ewell.BizComponent.Proxy.Model;
using Ewell.Interface.Common.Model.Common;
using Ewell.Interface.Common.Model.Config;
using Ewell.Interface.Common.Model.GateWay.Dto.Athena;
using Ewell.Interface.Common.Model.GateWay.GateWayUriInfo;
using Ewell.Interface.Common.Model.ProxyRequest;
using Ewell.Interface.Common.Utils;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Reflection;

namespace Ewell.BizComponent.Proxy
{
    public class BizProxy
    {
        public static bool isWin10 =  true;
        const string bizPregram = "Ewell.BizComponent.UI.Main.exe";
        /// <summary>
        /// 调用业务
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public InterfaceClientResult bizInvoke(string json)
        {
            
            BizRequest request = default;
            try
            {
                request = JsonConvert.DeserializeObject<BizRequest>(json);
            }
            catch (Exception ex)
            {
                LogHelper.Debug(ex.ToString());
                throw new SpeedException("业务代理", "传入的参数有误！" + json);
            }
            return this.bizInvoke(request);
        }
        public InterfaceClientResult bizInvoke(BizRequest request)
        {
            //接口代理日志
            LogHelper.Init("业务代理", $"BizProxy-{DateTime.Now.ToString("yyyy-MM-dd")}");
            LogHelper.Debug($"【业务代理】,传入参数:{JsonConvert.SerializeObject(request)}");
            LogHelper.Debug(Assembly.GetExecutingAssembly().Location.Substring(0, Assembly.GetExecutingAssembly().Location.LastIndexOf('\\')));
            LogHelper.Debug("11");
            Environment.CurrentDirectory = Assembly.GetExecutingAssembly().Location.Substring(0, Assembly.GetExecutingAssembly().Location.LastIndexOf('\\'));
            if (string.IsNullOrWhiteSpace(ProxyConfig.his_getway_url))
                ProxyConfig.his_getway_url = JsonConfig.ReadFullFileConfig(Path.Combine(Assembly.GetExecutingAssembly().Location.Substring(0, Assembly.GetExecutingAssembly().Location.LastIndexOf('\\')), (isWin10 ? "win10\\" : "win7\\")+"config\\package.json"), "his_getway_url");
            InterfaceClientResult result = new InterfaceClientResult() { success = true };
            try
            {
                ProxyHeader proxyHeader = JsonConvert.DeserializeObject<ProxyHeader>(request.header);
                CheckHeader(proxyHeader);
                if (string.IsNullOrWhiteSpace(request.authentication))
                {
                    ThirdLoginRequest thirdLogin = new ThirdLoginRequest()
                    {
                        userNo = proxyHeader.employeeNo,
                        userName = proxyHeader.employeeName,
                        zone = proxyHeader.zone,
                    };
                    UserDubboService userDubboService = new UserDubboService();
                    var gateWayUUHeader=userDubboService.thirdLogin.Post<UUHeader>(thirdLogin);
                    if (!gateWayUUHeader.success) throw new SpeedException("业务代理", gateWayUUHeader.message);
                    
                    request.authentication=JsonConvert.SerializeObject(gateWayUUHeader.@object);
                }
                string authentication = request.authentication;//用户信息
                //初始化用户
                try
                {
                    LoginInfo.loginUser = JsonConvert.DeserializeObject<User>(authentication);
                    JObject valuePairs = JObject.Parse(request.domain);
                    if (string.IsNullOrWhiteSpace(LoginInfo.loginUser.bizSourceCode))
                    {
                        try
                        {
                            LoginInfo.loginUser.bizSourceCode = valuePairs.GetValue("bizSourceCode").ToString();
                            request.authentication = JsonConvert.SerializeObject(LoginInfo.loginUser);
                        }
                        catch (Exception)
                        {
                            throw new SpeedException("业务代理", "bizSourceCode不能为空!");
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.Debug(ex.ToString());
                    throw new SpeedException("业务代理", "初始化登录信息出错!");
                }
                string prgram = (isWin10 ? "win10\\" : "win7\\") + bizPregram;
                result =ProcessHelper.ProcessInvoke(prgram, request);
                #region 废弃
                ////初始化接口日志
                //if (proxyHeader.tradeCode == "101")
                //{
                //    LogHelper.Init("业务接口", $"诊间挂号-{DateTime.Now.ToString("yyyy-MM-dd")}");
                //    BizMain bizMain = new BizMain();
                //    OutRegisterRequest registerRequest = JsonConvert.DeserializeObject<OutRegisterRequest>(request.domain);
                //    try
                //    {
                //        result.@object = bizMain.OutRegister(registerRequest);
                //    }
                //    catch (SpeedException ex)
                //    {
                //        result.success = false;
                //        result.message = ex.Message;
                //    }
                //    catch (Exception ex)
                //    {
                //        result.success = false;
                //        result.message = string.IsNullOrWhiteSpace(ex.InnerException?.InnerException?.Message) ? ex.InnerException?.Message : ex.InnerException?.InnerException?.Message;
                //    }
                //}
                //else if (proxyHeader.tradeCode == "201")
                //{
                //    LogHelper.Init("业务接口", $"诊间收费-{DateTime.Now.ToString("yyyy-MM-dd")}");
                //    Charge.BizMain bizMain = new Charge.BizMain();
                //    OutChargeRequest outChargeRequest = JsonConvert.DeserializeObject<OutChargeRequest>(request.domain);
                //    try
                //    {
                //        result.@object = bizMain.OutCharge(outChargeRequest);
                //        LogHelper.Debug(JsonConvert.SerializeObject(result));
                //    }
                //    catch (SpeedException ex)
                //    {
                //        result.success = false;
                //        result.message = ex.Message;
                //    }
                //    catch (Exception ex)
                //    {
                //        result.success = false;
                //        result.message = string.IsNullOrWhiteSpace(ex.InnerException?.InnerException?.Message) ? ex.InnerException?.Message : ex.InnerException?.InnerException?.Message;
                //    }
                //}
                #endregion
            }
            catch (SpeedException ex)
            {
                result.success = false;
                result.message = ex.Message;
            }
            catch (Exception ex)
            {
                result.success = false;
                result.message = string.IsNullOrWhiteSpace(ex.InnerException?.InnerException?.Message) ? ex.InnerException?.Message : ex.InnerException?.InnerException?.Message;
            }
            LogHelper.Init("业务代理", $"BizProxy-{DateTime.Now.ToString("yyyy-MM-dd")}");
            LogHelper.Debug($"【业务代理】,返回参数:{JsonConvert.SerializeObject(result)}");
            return result;
        }
        private void CheckHeader(ProxyHeader proxyHeader)
        {
            if (string.IsNullOrWhiteSpace(proxyHeader.employeeNo))
                throw new SpeedException("业务代理", "操作员工号不能为空！");
            if (string.IsNullOrWhiteSpace(proxyHeader.deptNo))
                throw new SpeedException("业务代理", "科室不能为空!");
            if (string.IsNullOrWhiteSpace(proxyHeader.zone))
                throw new SpeedException("业务代理", "院区不能为空!");
            if (string.IsNullOrWhiteSpace(proxyHeader.tradeCode))
                throw new SpeedException("业务代理", "交易编码不能为空!");
        }
    }
}
